﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Business;
using System.Web.Security;
using System.Web.Configuration;
using System.Configuration;

public partial class User_Shares_UploadDocumentsOthers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Lblstatus.Text = "";
        if (!IsPostBack)
        {
            var thisUser = HttpContext.Current.User;

            if (thisUser.IsInRole("Advisor")
                    || thisUser.IsInRole("Surveyor"))
            {
                MultiViewothers.ActiveViewIndex = 0;
                GridViewOthers.DataSource = DataAccess.TblContract.FetchByParameter(DataAccess.TblContract.Columns.UserId, Membership.GetUser().ProviderUserKey,SubSonic.OrderBy.Asc("ContractNumber"));
                GridViewOthers.DataBind();
            }
            else
                MultiViewothers.ActiveViewIndex = -1;
        }
    }
    protected void Multifileupload3_click(object sender, FileCollectionEventArgs e)
    {

        var thisUser = HttpContext.Current.User;
        Guid contractid = new Guid(Session["contractid"].ToString());
        DataAccess.TblContract con = new DataAccess.TblContract();
        con = DataAccess.TblContract.FetchByID(contractid);
        if (Session["stepid"] == null)
        {
            Lblstatus.Text = " <script>alert('. لطفا ابتدا مرحله مورد نظر را انتخاب کنید ')</script>";
        }
        else
        {  
            Guid stepid = new Guid(Session["stepid"].ToString());
      
            if (thisUser.IsInRole("advisor"))
            {
                IDataReader drad = DataAccess.TblStepsAdvisor.FetchByParameter("ID", stepid);
                drad.Read();
                if (drad["HasRepeat"].ToString() == "True")
                {
                    int Count = 0;
                    SubSonic.Query qad = DataAccess.TblTask.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.AddWhere("AdvisorStepId", SubSonic.Comparison.Equals, stepid);
                    qad.AddWhere("ContractId", SubSonic.Comparison.Equals, contractid);
                    qad.OrderBy = SubSonic.OrderBy.Desc("Date");
                    IDataReader dr = qad.ExecuteReader();
                    while (dr.Read())
                    {
                        Count += 1;
                    }
                    Guid taskid = new Guid(dr["ID"].ToString());
                    dr.Close();
                    if (Count <= Convert.ToInt32(drad["RepeatCount"]))
                    {
                        string folder = ConfigurationManager.AppSettings["saveFolder"];
                        bool result = FileTools.SaveFiles(e, HttpContext.Current, folder, taskid, Guid.Empty,DateTime.Now);
                        if (result == true)
                        {
                            DataAccess.TblTask insert = new DataAccess.TblTask();
                            insert.DateX = DateTime.Now;
                            insert.UserName = (Membership.GetUser().UserName);
                            insert.AdvisorStepId = stepid;
                            insert.ContractId = contractid;
                            insert.Save();
                            Business.Notification n = new Notification();
                            if (con.FourthFactorUserId != null)
                                n.SaveInnerNotific(contractid, stepid, true, new Guid(con.FourthFactorUserId.ToString()));
                            else
                                Lblstatus.Text = " <script>alert('. عامل چهاراین قرارداد برای ارسال پیغام تعریف نشده است ')</script>";

                            
                            if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                                n.SaveInnerNotific(contractid, stepid, true, n.findbonyadshahrestan(contractid));
                            else
                                Lblstatus.Text = " <script>alert('. بنیاد شهرستان این قرارداد برای ارسال پیغام تعریف نشده است ')</script>";
                            List<string> userids = new List<string>();
                            userids.Add(con.FourthFactorUserId.ToString());
                            userids.Add(n.findbonyadshahrestan(contractid).ToString());
                            string[] mobiles = n.FindMobile(userids);
                            SendSmS(mobiles);
              
                            Lblstatus.Text = " <script>alert('.فایل های شما با موفقیت ارسال شد ')</script>";
                        }
                        if (result == false)
                        {
                            Lblstatus.Text = " <script>alert('. ارسال فایل های شما با خطا مواجه شد ')</script>";
                        }
                    }
                    else
                    {
                        Lblstatus.Text = " <script>alert('. محدودیت در تکرار این مرحله: شما مجاز به ادامه این مرحله نیستید ')</script>";

                    }
                    drad.Close();
                }
                else
                {
                    SubSonic.Query qad = DataAccess.TblTask.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.AddWhere("AdvisorStepId", SubSonic.Comparison.Equals, stepid);
                    qad.AddWhere("ContractId", SubSonic.Comparison.Equals, contractid);
                    IDataReader dr = qad.ExecuteReader();
                    dr.Read();
                    Guid taskid = new Guid(dr["ID"].ToString());
                    dr.Close();
                    string folder = ConfigurationManager.AppSettings["saveFolder"];
                    bool result = FileTools.SaveFiles(e, HttpContext.Current, folder, taskid, Guid.Empty,DateTime.Now);
                    if (result == true)
                    {
                        SubSonic.Query update = DataAccess.TblTask.CreateQuery();
                        update.QueryType = SubSonic.QueryType.Update;
                        update.AddUpdateSetting(DataAccess.TblTask.Columns.DateX, DateTime.Now);
                        update.AddUpdateSetting(DataAccess.TblTask.Columns.UserName, Membership.GetUser().UserName);
                        update.AddWhere(DataAccess.TblTask.Columns.Id, taskid);
                        update.Execute();
                        Business.Notification n = new Notification();
                        if (con.FourthFactorUserId != null)
                            n.SaveInnerNotific(contractid, stepid, true, new Guid(con.FourthFactorUserId.ToString()));
                        else
                            Lblstatus.Text = " <script>alert('. عامل چهاراین قرارداد برای ارسال پیغام تعریف نشده است ')</script>";

                       
                        if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                            n.SaveInnerNotific(contractid, stepid, true, n.findbonyadshahrestan(contractid));
                        else
                            Lblstatus.Text = " <script>alert('. بنیاد شهرستان این قرارداد برای ارسال پیغام تعریف نشده است ')</script>";
              
                        Lblstatus.Text = " <script>alert('.فایل های شما با موفقیت ارسال شد ')</script>";
                        List<string> userids = new List<string>();
                        userids.Add(con.FourthFactorUserId.ToString());
                        userids.Add(n.findbonyadshahrestan(contractid).ToString());
                        string[] mobiles = n.FindMobile(userids);
                        SendSmS(mobiles);
                    }
                    if (result == false)
                    {
                        Lblstatus.Text = " <script>alert('. ارسال فایل های شما با خطا مواجه شد ')</script>";
                    }
                }
            }
            if (thisUser.IsInRole("surveyor"))
            {
                IDataReader drad = DataAccess.TblStepsSurveyor.FetchByParameter("ID", stepid);
                drad.Read();
                if (drad["HasRepeat"].ToString() == "True")
                {
                    int Count = 0;
                    SubSonic.Query qad = DataAccess.TblTask.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.AddWhere("SurveyorStepId", SubSonic.Comparison.Equals, stepid);
                    qad.AddWhere("ContractId", SubSonic.Comparison.Equals, contractid);
                    qad.OrderBy = SubSonic.OrderBy.Desc("Date");
                    IDataReader dr = qad.ExecuteReader();
                    while (dr.Read())
                    {
                        Count += 1;
                    }
                    Guid taskid = new Guid(dr["ID"].ToString());
                    dr.Close();
                    if (Count <= Convert.ToInt32(drad["RepeatCount"]))
                    {
                        string folder = ConfigurationManager.AppSettings["saveFolder"];
                        bool result = FileTools.SaveFiles(e, HttpContext.Current, folder, taskid, Guid.Empty,DateTime.Now);
                        if (result == true)
                        {
                            DataAccess.TblTask insert = new DataAccess.TblTask();
                            insert.DateX = DateTime.Now;
                            insert.UserName = (Membership.GetUser().UserName);
                            insert.AdvisorStepId = stepid;
                            insert.ContractId = contractid;
                            insert.Save();
                            Business.Notification n = new Notification();
                            if (con.FourthFactorUserId != null)
                                n.SaveInnerNotific(contractid, stepid, false, new Guid(con.FourthFactorUserId.ToString()));
                            else
                                Lblstatus.Text = " <script>alert('. عامل چهاراین قرارداد برای ارسال پیغام تعریف نشده است ')</script>";

                           
                            if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                                n.SaveInnerNotific(contractid, stepid, false, n.findbonyadshahrestan(contractid));
                            else
                                Lblstatus.Text = " <script>alert('. بنیاد شهرستان این قرارداد برای ارسال پیغام تعریف نشده است ')</script>";
              
                            Lblstatus.Text = " <script>alert('.فایل های شما با موفقیت ارسال شد ')</script>";
                            List<string> userids = new List<string>();
                            userids.Add(con.FourthFactorUserId.ToString());
                            userids.Add(n.findbonyadshahrestan(contractid).ToString());
                            string[] mobiles = n.FindMobile(userids);
                            SendSmS(mobiles);
                        }
                        if (result == false)
                        {
                            Lblstatus.Text = " <script>alert('. ارسال فایل های شما با خطا مواجه شد ')</script>";
                        }
                    }
                    else
                    {
                        Lblstatus.Text = " <script>alert('. محدودیت در تکرار این مرحله: شما مجاز به ادامه این مرحله نیستید ')</script>";

                    }
                    drad.Close();
                }
                else
                {
                    SubSonic.Query qad = DataAccess.TblTask.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.AddWhere("SurveyorStepId", SubSonic.Comparison.Equals, stepid);
                    qad.AddWhere("ContractId", SubSonic.Comparison.Equals, contractid);
                    IDataReader dr = qad.ExecuteReader();
                    dr.Read();
                    Guid taskid = new Guid(dr["ID"].ToString());
                    dr.Close();
                    string folder = ConfigurationManager.AppSettings["saveFolder"];
                    bool result = FileTools.SaveFiles(e, HttpContext.Current, folder, taskid, Guid.Empty,DateTime.Now);
                    if (result == true)
                    {
                        SubSonic.Query update = DataAccess.TblTask.CreateQuery();
                        update.QueryType = SubSonic.QueryType.Update;
                        update.AddUpdateSetting(DataAccess.TblTask.Columns.DateX, DateTime.Now);
                        update.AddUpdateSetting(DataAccess.TblTask.Columns.UserName, Membership.GetUser().UserName);
                        update.AddWhere(DataAccess.TblTask.Columns.Id, taskid);
                        update.Execute();
                        Business.Notification n = new Notification();
                        if (con.FourthFactorUserId != null)
                            n.SaveInnerNotific(contractid, stepid, false, new Guid(con.FourthFactorUserId.ToString()));
                        else
                            Lblstatus.Text = " <script>alert('. عامل چهاراین قرارداد برای ارسال پیغام تعریف نشده است ')</script>";

                     
                        if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                            n.SaveInnerNotific(contractid, stepid, false, n.findbonyadshahrestan(contractid));
                        else
                            Lblstatus.Text = " <script>alert('. بنیاد شهرستان این قرارداد برای ارسال پیغام تعریف نشده است ')</script>";
              
                        Lblstatus.Text = " <script>alert('.فایل های شما با موفقیت ارسال شد ')</script>";

                        List<string> userids = new List<string>();
                        userids.Add(con.FourthFactorUserId.ToString());
                        userids.Add(n.findbonyadshahrestan(contractid).ToString());
                        string[] mobiles = n.FindMobile(userids);
                        SendSmS(mobiles);

                    }
                    if (result == false)
                    {
                        Lblstatus.Text = " <script>alert('. ارسال فایل های شما با خطا مواجه شد ')</script>";
                    }
                }
            }
        }
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        var thisUser = HttpContext.Current.User;
        if (Session["stepid"] == null)
        {
            Lblstatus.Text = " <script>alert('. لطفا ابتدا مرحله مورد نظر را انتخاب کنید ')</script>";
        }
        else
        {
            if (thisUser.IsInRole("advisor"))
            {
                Guid stepid = new Guid(Session["stepid"].ToString());
                Guid contractid = new Guid(Session["contractid"].ToString());
                //int days = 0;
                IDataReader dr = DataAccess.TblTask.FetchByParameter(DataAccess.TblTask.Columns.ContractId, contractid);


                SubSonic.Query update = DataAccess.TblTask.CreateQuery();
                update.QueryType = SubSonic.QueryType.Update;
                update.AddUpdateSetting(DataAccess.TblTask.Columns.DateX, DateTime.Now);
                update.AddUpdateSetting(DataAccess.TblTask.Columns.IsDonei, bool.TrueString);
                //update.AddUpdateSetting(DataAccess.TblTask.Columns.DelayDays, days);
                update.AddUpdateSetting(DataAccess.TblTask.Columns.UserName, Membership.GetUser().UserName);
                update.AddWhere(DataAccess.TblTask.Columns.AdvisorStepId, stepid.ToString());
                update.AddWhere(DataAccess.TblTask.Columns.ContractId, contractid.ToString());
                update.Execute();
                Lblstatus.Text = " <script>alert('. مرحله مورد نظر شما به تاریخ امروز پایان یافته اعلام شد ')</script>";
          
                DataAccess.TblContract con = new DataAccess.TblContract();
                con = DataAccess.TblContract.FetchByID(contractid);
                Business.Notification n = new Notification();
                if (con.FourthFactorUserId != null)
                    n.SaveInnerNotificEnd(contractid, stepid, true, new Guid(con.FourthFactorUserId.ToString()));
              
                if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                    n.SaveInnerNotificEnd(contractid, stepid, true, n.findbonyadshahrestan(contractid));
                List<string> userids = new List<string>();
                userids.Add(con.FourthFactorUserId.ToString());
                userids.Add(n.findbonyadshahrestan(contractid).ToString());
                string[] mobiles = n.FindMobile(userids);
                SendSmS(mobiles);

            }
            if (thisUser.IsInRole("surveyor"))
            {
                Guid stepid = new Guid(Session["stepid"].ToString());
                Guid contractid = new Guid(Session["contractid"].ToString());

                SubSonic.Query update = DataAccess.TblTask.CreateQuery();
                update.QueryType = SubSonic.QueryType.Update;
                update.AddUpdateSetting(DataAccess.TblTask.Columns.DateX, DateTime.Now);
                update.AddUpdateSetting(DataAccess.TblTask.Columns.IsDonei, true);
                //update.AddUpdateSetting(DataAccess.TblTask.Columns.DelayDays, days);
                update.AddUpdateSetting(DataAccess.TblTask.Columns.UserName, Membership.GetUser().UserName);
                update.AddWhere(DataAccess.TblTask.Columns.SurveyorStepId, stepid.ToString());
                update.AddWhere(DataAccess.TblTask.Columns.ContractId, contractid.ToString());
                update.Execute();
                Lblstatus.Text = " <script>alert('. مرحله مورد نظر شما به تاریخ امروز پایان یافته اعلام شد ')</script>";
                DataAccess.TblContract con = new DataAccess.TblContract();
                con = DataAccess.TblContract.FetchByID(contractid);
                Business.Notification n = new Notification();
                if (con.FourthFactorUserId != null)
                    n.SaveInnerNotificEnd(contractid, stepid, false, new Guid(con.FourthFactorUserId.ToString()));
               

                if (n.findbonyadshahrestan(contractid) != Guid.Empty)
                    n.SaveInnerNotificEnd(contractid, stepid, false, n.findbonyadshahrestan(contractid));
                List<string> userids = new List<string>();
                userids.Add(con.FourthFactorUserId.ToString());
                userids.Add(n.findbonyadshahrestan(contractid).ToString());
                string[] mobiles = n.FindMobile(userids);
                SendSmS(mobiles);
              
            }
        }
    }
    protected void Button7_Click(object sender, EventArgs e)
    {
        MultiViewothers.ActiveViewIndex = 0;
        DataList2.DataSource = null;
        DataList2.DataBind();
    }
    protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        Guid contractid = new Guid(Session["contractid"].ToString());
        if (DataList2.SelectedItem.ItemIndex < 0)
        {
            Session["stepid"] = null;
        }
        else
        {
            var thisUser = HttpContext.Current.User;
            SubSonic.Query qad = DataAccess.TblTask.CreateQuery();
            qad.QueryType = SubSonic.QueryType.Select;
            if (thisUser.IsInRole("advisor"))
                qad.AddWhere("AdvisorStepId", SubSonic.Comparison.Equals, DataList2.SelectedValue);
            else if (thisUser.IsInRole("surveyor"))
            qad.AddWhere("SurveyorStepId", SubSonic.Comparison.Equals, DataList2.SelectedValue);
            qad.AddWhere("ContractId", SubSonic.Comparison.Equals, contractid);
            IDataReader dr = qad.ExecuteReader();
            dr.Read();
            string Desc = dr["Status"].ToString();
            LblDesc.Text = Desc;
            dr.Close();
            Session["stepid"] = DataList2.SelectedValue;
        }
    }
    protected void GridViewOthers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int id = Convert.ToInt32(e.CommandArgument);
        switch (e.CommandName)
        {
            case "Select":
                Guid contractid = new Guid(GridViewOthers.DataKeys[id].Value.ToString());
                Session["contractid"] = contractid;
                SubSonic.Query q = DataAccess.TblTask.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.AddWhere(DataAccess.TblTask.Columns.ContractId, contractid);
                q.AddWhere(DataAccess.TblTask.Columns.IsDonei, true);
                IDataReader dr = q.ExecuteReader();
                int i = 0;
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        i += 1;
                    }
                }
                dr.Close();
                var thisUser = HttpContext.Current.User;

                if (thisUser.IsInRole("advisor"))
                {
                    SubSonic.Query qad = DataAccess.TblStepsAdvisor.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.BETWEEN_VALUES("Priority", 0, i + 1);
                    qad.OrderBy = SubSonic.OrderBy.Asc("Priority");

                    DataList2.DataSource = qad.ExecuteReader();
                    DataList2.DataBind();
                }
                if (thisUser.IsInRole("surveyor"))
                {
                    SubSonic.Query qad = DataAccess.TblStepsSurveyor.CreateQuery();
                    qad.QueryType = SubSonic.QueryType.Select;
                    qad.BETWEEN_VALUES("Priority", 0, i + 1);
                    qad.OrderBy = SubSonic.OrderBy.Asc("Priority");

                    DataList2.DataSource = qad.ExecuteReader();
                    DataList2.DataBind();
                }
                LblDate0.Text = GridViewOthers.Rows[id].Cells[1].Text;
                lblvilname0.Text = GridViewOthers.Rows[id].Cells[5].Text;
                LblConNum0.Text = GridViewOthers.Rows[id].Cells[0].Text;
                MultiViewothers.ActiveViewIndex = 1;
                break;
        }
    }

    protected void GridViewOthers_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridViewOthers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType
                 == DataControlRowType.DataRow)
            {
                Business.Calender cal = new Business.Calender();
                string pdate = cal.MiladiToPersian(Convert.ToDateTime(e.Row.Cells[1].Text));
                e.Row.Cells[1].Text = pdate;
                IDataReader t = DataAccess.TblUserDetail.FetchByParameter(DataAccess.TblUserDetail.Columns.UserId, e.Row.Cells[9].Text);
                if (t.Read())
                {
                    e.Row.Cells[2].Text = t["Name"].ToString() + " / " + t["Family"].ToString();
                    t.Close();
                }

                if (e.Row.Cells[3].Text == bool.TrueString)
                    e.Row.Cells[3].Text = "قرارداد مشاوره";
                if (e.Row.Cells[3].Text == bool.FalseString)
                    e.Row.Cells[3].Text = "قرارداد نقشه برداری";
                DataAccess.TblVillage vil = DataAccess.TblVillage.FetchByID(e.Row.Cells[11].Text);
                e.Row.Cells[5].Text = vil.Name;
                DataAccess.TblDehestan deh = DataAccess.TblDehestan.FetchByID(vil.DehstanId);
                e.Row.Cells[6].Text = deh.Name;
                DataAccess.TblBakhsh bakhsh = DataAccess.TblBakhsh.FetchByID(deh.BakhshId);
                e.Row.Cells[7].Text = bakhsh.Name;
                DataAccess.TblCity city = DataAccess.TblCity.FetchByID(bakhsh.CityId);
                e.Row.Cells[8].Text = city.Name;
                e.Row.Cells[9].Visible = false;
                e.Row.Cells[11].Visible = false;
            }
        }
        catch
        {
        }
    }
    public void SendSmS(string[] D)
    {
        com.sobhsms.www.Service1 s = new com.sobhsms.www.Service1();

        string str = "لطفاهرچه سریعتربه وبسایت www.bonyadmaskanfars.ir/fpm مراجعه بفرمایید.";
        str = str.Replace("@", Environment.NewLine);

        if (D.Length >0)
        {
            long[] r = s.SendPackageMessageConcFast(D, str, "Pwebsrvbnydmskn90");
        }
        //Response.Write(r[0].ToString());
    }
}